<template>
    <basic-container>
        <avue-crud :option="option"
                   :data="data"
                   ref="crud"
                   v-model="form"
                   :table-loading="loading"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   :page="page"
                   @refresh-change="refreshChange"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoad">
            <template slot-scope="{row}"
                      slot="status">
                <el-switch @change="rowSwitchChange(row)"
                           v-model="row.status"
                           active-value="ENABLE"
                           inactive-value="DISABLE">
                </el-switch>
            </template>

            <template slot-scope="{row,type,size}"
                      slot="menu">
                <el-button :type="type"
                           :size="size"
                           icon="el-icon-thumb"
                           @click="setLeader(row)" v-if="row.roleId==3">设置上级</el-button>
                <el-button :type="type"
                           :size="size"
                           icon="el-icon-refresh-right"
                           @click="earnDetail(row.userId)">收益详情</el-button>
            </template>
        </avue-crud>

        <el-dialog :visible.sync="dialogVisible"
                   class="dialogResech"
                   title="设置上级"
                   width="70%" @close="closeDialog">
                    <el-row type="flex" class="row-bg" style="margin-bottom: 30px;">
                        <el-col :span="6">
                            <el-input v-model="searchInput" placeholder="请输入手机号"  ></el-input>
                        </el-col>
                        <el-col :span="12" style="margin-left: 20px;">
                            <el-button type="primary" icon="el-icon-search" @click="selectUser()">搜索</el-button>
                        </el-col>
                    </el-row>
                    <el-table :data="resucedata" ref="selectionChangeTable" border
                            size="small"
                            style="width: 100%"
                            @row-click="tableClick"
                            @selection-change="selectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="account" label="账号" width="180"></el-table-column>
                        <el-table-column prop="phone" label="手机号"></el-table-column>
                        <el-table-column prop="name" label="姓名" ></el-table-column>
                        <el-table-column prop="roleName" label="类型"></el-table-column>
                    </el-table>
                    <el-pagination
                            @size-change="sizeChangeT"
                            @current-change="currentChangeT"
                            :current-page="pageT.currentPage"
                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                            :page-size="pageT.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="pageT.total">
                    </el-pagination>
                    <el-row style="margin-top: 20px;">
                        <span class="dialog-footer">
                            <el-button @click="closeDialog">取 消</el-button>
                            <el-button type="primary" @click="setLeaderSubmit">提交</el-button>
                        </span>
                    </el-row>
        </el-dialog>

        <el-dialog title="收益详情"  width="80%" :visible.sync="dialogVisibleB">
            <avue-crud :option="optionB" :data="resucedataB"  v-model="formB" :table-loading="loading"
                       @date-change="dateChange" :page="pageB" @refresh-change="refreshChangeB" @search-change="searchChangeB" @current-change="currentChangeB" @size-change="sizeChangeB">
            </avue-crud>
        </el-dialog>

    </basic-container>
</template>
<script>
    import {getList,changeStatus,getLeaderList,setUserLeader,getProfitList} from "@/api/minmao/mgr/userMgr";
    import { mapGetters } from "vuex";
    import {
        testPhone
    } from '@/util/util';
    var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
    var userId = 0;
    export default {
        watch:{
        },
        data () {
            return {
                searchInput:'',
                multipleSelection:[],
                addLoadU:false,
                flag:true,
                userFrom:{},
                display: true,
                dialogVisible:false,
                dialogVisibleB:false,
                form: {},
                formB:{},
                checkdata: '',
                query: {},
                queryT: {},
                queryB: {},
                loading: true,
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                pageT: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                pageB: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                option: {
                    size: 'mini',
                    tip: false,
                    border: true,
                    index: true,
                    rowKey: 'userId',
                    height: 'auto',
                    // calcHeight: 380,
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    dialogType: 'dialog',
                    menuWidth: 240,
                    searchMenuSpan:6,
                    column: [
                        {
                            label: "账号",
                            prop: "account",
                            search: true,
                            fixed: true,
                            rules: [{
                                required: true,
                                message: "请输入账号",
                                trigger: "blur"
                            } ]
                        },
                        {
                            label: '手机号',
                            prop: 'phone',
                            width: 120,
                            rules: [{
                                required: true,
                                message: "请输入电话",
                                trigger: "blur"
                            },
                                {
                                    validator: testPhone,
                                    trigger: 'blur'
                                },
                            ]
                        },
                        {
                            label: "密码",
                            prop: "password",
                            type: 'password',
                            hide: true,
                            rules: [{
                                required: true,
                                message: "请输入密码",
                                trigger: "blur"
                            }]
                        },
                        {
                            label: "姓名",
                            prop: "name",
                            rules: [{
                                required: true,
                                message: "请输入姓名",
                                trigger: "blur"
                            }]
                        },
                        {
                            search: true,
                            label: "类型",
                            prop: "roleName",
                            type: "select",
                            dicData: Dict.roleKindEnum,
                        },
                        {
                            label: "账号状态",
                            prop: "status",
                            slot: true,
                            type: 'switch',
                            dicData: [
                                {
                                    label: "关闭",
                                    value: 'DISABLE'
                                },
                                {
                                    label: "开启",
                                    value: 'ENABLE'
                                },
                            ],
                        },
                        {
                            label: "上级",
                            prop: "parentName",
                        },
                        {
                            label: "上级类型",
                            prop: "parentRoleName",
                            width: 180,
                        }
                    ]
                },
                optionA: {
                    page: true,
                    align: 'center',
                    menuAlign: 'center',
                    size: 'mini',
                    excelBtn: false,
                    addBtn: false,
                    tip: false,
                    border: true,
                    viewBtn: false,
                    editBtn: false,
                    "searchBtn": false,
                    "printBtn": false,
                    "columnBtn": false,
                    "refreshBtn": false,
                    "menu": false,
                    "filterBtn": false,
                    delBtn: false,
                    height: 'auto',
                    calcHeight: 200,
                    rowKey: 'userId',
                    searchMenuSpan:6,
                    column: [
                        {
                            label:'选择上级',
                            prop:'userId',
                            slot:true
                        },
                        {
                            label: "账号",
                            prop: "account",
                        },
                        {
                            label: "手机号",
                            prop: "phone",
                            search: true,
                        },
                        {
                            label: "姓名",
                            prop: "name",
                        },
                        {
                            label: "类型",
                            prop: "roleName",
                        },
                    ]
                },
                optionB: {
                    page: true,
                    size: 'mini',
                    tip: false,
                    border: true,
                    index: false,
                    rowKey: 'userId',
                    height: 'auto',
                    // calcHeight: 380,
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    dialogType: 'dialog',
                    menuWidth: 240,
                    searchMenuSpan:6,
                    menu:false,
                    dateBtn:true,
                    column: [
                        {
                            label: "受益人",
                            prop: "name",

                        },
                        {
                            label: "受益人手机号",
                            prop: "phone",
                        },
                        {
                            label: "交易类型",
                            prop: "tradeType",
                            dicData: Dict.tradeTypeEnum,
                        },
                        {
                            label: "金额",
                            prop: "amount",
                        },
                        {
                            label: "流水状态",
                            prop: "lockStatus",
                            dicData: Dict.lockStatusEnum,
                        },
                        {
                            label: "时间",
                            prop: "addTime",

                        },
                    ]
                },
                resucedata: [],
                resucedataB: [],
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission", 'userInfo']),
            permissionList () {
                return {

                };
            },
        },
        methods: {
            selectionChange(val){
                if(val.length > 1){
                    this.$refs.selectionChangeTable.clearSelection();
                    this.$refs.selectionChangeTable.toggleRowSelection(val.pop())
                }else{
                    this.multipleSelection = val.pop();
                    if (this.multipleSelection!=undefined){
                        this.checkdata = this.multipleSelection.userId;
                    }
                }
            },
            tableClick(row){
                //再次点击选中的记录时取消选中效果并清空checkdata数据
                if (this.checkdata == row.userId){
                    this.checkdata = '';
                }else{
                    this.checkdata = row.userId;
                }
                this.$refs.selectionChangeTable.toggleRowSelection(row)
            },
            //清空
            refreshChangeT () {
                this.onLoadT(this.pageT);
            },
            refreshChangeB() {
                this.onLoadB(this.pageB);
            },
            //搜索(搜索，可以搜索任意资源但不带menuId)
            searchChangeT (params,done) {
                this.query = params;
                this.onLoadB(this.pageT, this.query,done);
            },
            searchChangeB (params,done) {
                this.query = params;
                this.onLoadB(this.pageB, this.query,done);
            },
            // 监听pagenum改变
            currentChangeT (currentPage) {
                this.pageT.currentPage = currentPage;
                console.log(this.query)
                this.onLoadT(this.pageT);
            },
            currentChangeB(currentPage) {
                this.pageB.currentPage = currentPage;
                this.onLoadB(this.pageB);
            },
            //  监听pageSize改变
            sizeChangeT (pageSize) {
                this.pageT.pageSize = pageSize;
                this.onLoadT(this.pageT);
            },
            //  监听pageSize改变
            sizeChangeB (pageSize) {
                this.pageB.pageSize = pageSize;
                this.onLoadB(this.pageB);
            },
            //设置上级弹框的页面加载
            onLoadT (pageT, params = {}) {
                getLeaderList(pageT.currentPage, pageT.pageSize, Object.assign(params, this.queryT)).then(res => {
                    if(res.status==200){
                        this.resucedata = [];
                        const data = res.data;
                        this.pageT.total = data.count;
                        this.resucedata = data.data;
                    }
                });
            },
            //收益详情弹框的页面加载
            onLoadB (pageB, params = {},done) {
                getProfitList(pageB.currentPage, pageB.pageSize, Object.assign(params, this.query)).then(res => {
                    if(done){
                        done();
                    }
                    if(res.status==200){
                        this.resucedataB = [];
                        const data = res.data;
                        this.pageB.total = data.count;
                        this.resucedataB = data.data;
                    }
                });
            },
            handleEmpty(){
                this.$refs["diaformRef"].resetForm();
                this.addLoadU=false
            },
            editHandleEmpty(){
                this.$refs["diaEditFormRef"].resetForm();
            },
            handleSetRoles () {
                console.log(this.form.userId)
                console.log(this.form.roleId)
                if(this.form.roleId){
                    if( this.form.userId != 1 && this.form.roleId==1){
                        this.$message({
                            type:'warning',
                            message:'不能设置超级管理员'
                        })
                        return
                    }else{
                        if(this.form.userId && this.form.roleId){
                            setRoles(this.form.userId, this.form.roleId).then(res => {
                                if(res.data.code==200){
                                    this.flag = true;
                                    this.$message.success('设置成功');
                                    this.onLoad(this.page);
                                    this.form = {}
                                }
                            })
                        }else{
                            return
                        }
                    }
                }
                else{
                    this.$message.error("请至少给该用户分配一个权限");
                }

            },
            //设置上级
            setLeader (row) {
                this.dialogVisible = true;
                this.queryT.userId = row.userId;
                this.onLoadT(this.pageT);
            },
            //根据手机号搜索
            selectUser(){
                this.queryT.phone = this.searchInput;
                this.onLoadT(this.pageT);
            },
            //账号状态改变
            rowSwitchChange (row) {
                if (row.status === 'ENABLE') {
                    changeStatus(row.userId, 'unfreeze');
                } else {
                    changeStatus(row.userId, 'freeze');
                }
            },
            searchReset () {
                this.query = {};
                this.onLoad(this.page);
            },
            //弹窗关闭
            closeDialog () {
                this.checkdata = '';
                //清空搜索手机号
                this.searchInput='';
                this.dialogVisible = false;
            },
            //设置上级提交
            setLeaderSubmit(){
                console.log(this.checkdata)
                if( this.checkdata == ''){
                    this.$message({
                        type:'error',
                        message:'请选择一条记录设置为上级'
                    })
                    return
                }
                const userId = this.queryT.userId;
                //选中用户的id
                const chosedUserId = this.checkdata;
                setUserLeader(userId,chosedUserId).then(res =>{
                    this.dialogVisible = false;
                    this.queryT = {};
                    this.onLoad(this.page);
                })
            },
            searchChange (params,done) {
                //每次搜索，都从第一页开始查询
                this.page.currentPage=1;
                //接口是用roleId接收的
                params.roleId = params.roleName;
                this.query = params;
                this.onLoad(this.page, params,done);
            },
            //收益详情
            earnDetail (id) {
                this.dialogVisibleB = true;
                this.query.userId = id;
                userId = id;
                this.onLoadB(this.pageB);
            },
            beforeOpen (done, type) {
                if (["edit", "view"].includes(type)) {
                    getUser(this.form.userId).then(res => {
                        this.form = res.data.data;
                        this.form.positionIds = this.form.positionIds.split(',');
                    });
                }
                done();
                setTimeout(() => {
                    if ('add' === type) {
                        this.form.status = 'ENABLE'
                    }
                }, 0)

            },
            currentChange (currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange (pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange () {
                this.onLoad(this.page);
            },
            onLoad (page, params = {},done) {
                this.loading = true;
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    if(done){
                        done();
                    }
                    this.loading = false;
                    const data = res.data;
                    this.page.total = data.count;
                    this.data = data.data;
                });
            },
            dateChange(date){
                let beginTime = date[0];
                let endTime = date[1];
                this.query.beginTime = beginTime;
                this.query.endTime = endTime;
                this.query.userId = userId;
                this.onLoadB(this.pageB, this.query);
            }
        }
    };
</script>

<style>
</style>
